let gameState = {
    player: {
        level: 1,
        gold: 100,
        hand: [],
        battle: [],
        maxHandSize: 6,
        health: 30
    },
    opponent: {
        level: 1,
        gold: 100,
        hand: Array.from({length: 6}, () => Math.floor(Math.random() * 18) + 1),
        battle: [],
        health: 30
    },
    availableCards: new Array(6).fill(0),
    timer: 20,
    round: 1,
    isRoundEnd: false,
    timerInterval: null
};

function initGame() {
    refreshCards();
    updateDisplay();
    startTimer();
    
    // 設置對手AI行動
    setInterval(() => {
        if (!gameState.isRoundEnd) {
            performOpponentTurn();
        }
    }, 2000); // 每2秒對手可能行動一次
}

function generateOpponentHand() {
    // 獲取所有可用的卡牌ID（count > 0的卡牌）
    const availableCardIds = Object.entries(cardConfig.cards)
        .filter(([_, card]) => card.count > 0)
        .map(([id, _]) => parseInt(id));
    
    // 如果沒有可用卡牌，直接返回
    if (availableCardIds.length === 0) {
        return;
    }
    
    // 為對手生成手牌
    gameState.opponent.hand = Array.from({length: 6}, () => {
        const randomIndex = Math.floor(Math.random() * availableCardIds.length);
        const cardId = availableCardIds[randomIndex];
        cardConfig.decreaseCardCount(cardId); // 減少卡牌數量
        return cardId;
    });
}

function refreshCards() {
    // 檢查金幣是否足夠
    if(parseInt(gameState.player.gold) < 2) {
        alert('金幣不足！需要2金幣刷新卡牌。');
        return;
    }
    
    // 獲取所有可用的卡牌ID（count > 0的卡牌）
    const availableCardIds = Object.entries(cardConfig.cards)
        .filter(([_, card]) => card.count > 0)
        .map(([id, _]) => parseInt(id));
    
    console.log('可用的卡牌ID:', availableCardIds);
    
    // 如果沒有可用卡牌，直接返回
    if (availableCardIds.length === 0) {
        alert('沒有可用的卡牌了！');
        return;
    }
    
    // 扣除金幣
    gameState.player.gold = parseInt(gameState.player.gold) - 2;
    
    // 隨機選擇卡牌
    gameState.availableCards = Array.from({length: 6}, () => {
        const randomIndex = Math.floor(Math.random() * availableCardIds.length);
        const selectedId = availableCardIds[randomIndex];
        console.log('選擇的卡牌ID:', selectedId);
        return selectedId;
    });
    
    //console.log('刷新後的可用卡牌:', gameState.availableCards);
    updateDisplay();
}

function upgrade() {
    // 檢查金幣是否足夠
    if(parseInt(gameState.player.gold) < 5) {
        alert('金幣不足！需要5金幣升級。');
        return;
    }
    
    gameState.player.gold = parseInt(gameState.player.gold) - 5;
    gameState.player.level++;
    updateDisplay();
}

function addToHand(cardId) {
    // 檢查手牌是否已滿
    if (gameState.player.hand.length >= gameState.player.maxHandSize) {
        alert('手牌已滿！');
        return;
    }
    
    const cardInfo = cardConfig.getCardInfo(cardId);
    
    if (!cardInfo) {
        alert('無效的卡牌！');
        return;
    }
    
    // 檢查金幣是否足夠
    if (parseInt(gameState.player.gold) < cardInfo.cost) {
        alert(`金幣不足！需要${cardInfo.cost}金幣購買此卡牌。`);
        return;
    }
    
    // 檢查卡牌是否還有剩餘數量
    if (cardConfig.decreaseCardCount(cardId)) {
        gameState.player.gold = parseInt(gameState.player.gold) - cardInfo.cost;
        gameState.player.hand.push(cardId);

        // 購買成功後，將該卡牌從 availableCards 中移除
        const idx = gameState.availableCards.indexOf(cardId);
        if (idx !== -1) gameState.availableCards.splice(idx, 1);

        // 更新顯示
        updateDisplay();
        
        // 檢查是否可以合成
        checkCardMerge();
    } else {
        alert('該卡牌已用完！');
    }
}

// 檢查並處理卡牌合成
function checkCardMerge() {
    // 合併手牌和出牌區的卡牌
    const allCards = [...gameState.player.hand, ...gameState.player.battle];
    const cardCounts = {};
    
    // 統計每張卡牌的數量
    allCards.forEach(cardId => {
        cardCounts[cardId] = (cardCounts[cardId] || 0) + 1;
    });
    
    // 檢查是否有可以合成的卡牌
    for (const [cardId, count] of Object.entries(cardCounts)) {
        if (count >= 3) {
            // 從手牌和出牌區移除這三張卡
            let removedCount = 0;
            
            // 先從手牌中移除
            for (let i = gameState.player.hand.length - 1; i >= 0 && removedCount < 3; i--) {
                if (gameState.player.hand[i] === parseInt(cardId)) {
                    gameState.player.hand.splice(i, 1);
                    removedCount++;
                }
            }
            
            // 再從出牌區移除
            for (let i = gameState.player.battle.length - 1; i >= 0 && removedCount < 3; i--) {
                if (gameState.player.battle[i] === parseInt(cardId)) {
                    gameState.player.battle.splice(i, 1);
                    removedCount++;
                }
            }
            
            // 創建新的合成卡牌
            const mergedCardId = parseInt(cardId);
            const cardInfo = cardConfig.getCardInfo(mergedCardId);
            
            // 更新卡牌配置，標記為合成卡牌
            cardConfig.cards[mergedCardId] = {
                ...cardInfo,
                attack: cardInfo.attack * 2,
                defense: cardInfo.defense * 2,
                isMerged: true
            };
            
            // 將合成卡牌添加到出牌區
            gameState.player.battle.push(mergedCardId);
            
            // 更新顯示
            updateDisplay();
            
            // 顯示合成特效
            showMergeEffect(mergedCardId);
            
            // 繼續檢查是否還有其他可以合成的卡牌
            checkCardMerge();
            break;
        }
    }
}

// 顯示合成特效
function showMergeEffect(cardId) {
    const cardElement = document.querySelector(`#player-battle .card[style*="${cardId}.png"]`);
    if (cardElement) {
        cardElement.classList.add('merged-card');
        // 延長特效時間到3秒
        setTimeout(() => {
            cardElement.classList.remove('merged-card');
        }, 3000);
    }
}

// 修改 playCard 函數，在出牌後檢查合成
function playCard(cardId) {
    // 檢查是否在回合結束狀態
    if (gameState.isRoundEnd) {
        alert('回合已結束！');
        return;
    }

    // 檢查手牌中是否有這張卡
    const index = gameState.player.hand.indexOf(cardId);
    if (index === -1) {
        console.error('找不到要出的卡牌');
        return;
    }

    // 檢查戰場是否已滿（根據等級限制）
    if (gameState.player.battle.length >= gameState.player.level) {
        alert(`戰場已滿！當前等級${gameState.player.level}，最多只能放置${gameState.player.level}張卡牌`);
        return;
    }

    // 出牌
    const playedCard = gameState.player.hand.splice(index, 1)[0];
    gameState.player.battle.push(playedCard);
    
    // 檢查是否可以合成
    checkCardMerge();
    
    updateDisplay();
    
    // 檢查是否該結束回合
    if (gameState.timer <= 0) {
        endRound();
    }
}

function endRound() {
    gameState.isRoundEnd = true;
    
    // 執行戰鬥
    resolveBattle();
    
    // 開始新回合
    startNewRound();
}

function startNewRound() {
    gameState.round++;
    gameState.timer = 20;
    gameState.isRoundEnd = false;
    
    gameState.player.gold = parseInt(gameState.player.gold) + 2;
    // 自動刷新一次卡牌
    refreshCards();
    
    // 重新開始計時器
    startTimer();
    
    // 更新顯示
    updateDisplay();
}

function performOpponentTurn() {
    // 對手AI邏輯
    if (gameState.opponent.hand.length > 0 && gameState.opponent.battle.length < gameState.opponent.level) {
        const randomCard = gameState.opponent.hand.pop();
        gameState.opponent.battle.push(randomCard);
        updateDisplay();
    }
}

function resolveBattle() {
    // 計算雙方戰鬥力
    const playerPower = calculateBattlePower(gameState.player.battle);
    const opponentPower = calculateBattlePower(gameState.opponent.battle);
    
    // 計算傷害（攻擊力減去對方防禦力）
    const playerDamage = Math.max(0, playerPower.attack - opponentPower.defense);
    const opponentDamage = Math.max(0, opponentPower.attack - playerPower.defense);
    
    // 應用傷害
    gameState.opponent.health -= opponentDamage;
    gameState.player.health -= playerDamage;
    
    // 根據勝負給予金幣獎勵
    if (playerDamage > opponentDamage) {
        gameState.player.gold = parseInt(gameState.player.gold) + 10; // 勝利獲得10金幣
        gameState.opponent.gold = parseInt(gameState.opponent.gold) + 7; // 失敗獲得7金幣
    } else if (opponentDamage > playerDamage) {
        gameState.opponent.gold = parseInt(gameState.opponent.gold) + 10; // 勝利獲得10金幣
        gameState.player.gold = parseInt(gameState.player.gold) + 7; // 失敗獲得7金幣
    } else {
        // 平局雙方都獲得7金幣
        gameState.player.gold = parseInt(gameState.player.gold) + 7;
        gameState.opponent.gold = parseInt(gameState.opponent.gold) + 7;
    }
    
    // 檢查遊戲是否結束
    checkGameEnd();

    console.log(`玩家攻擊:${playerPower.attack} 防禦:${playerPower.defense}`);
    console.log(`對手攻擊:${opponentPower.attack} 防禦:${opponentPower.defense}`);
}

function calculateBattlePower(battleCards) {
    return battleCards.reduce((total, card) => {
        const cardPower = cardConfig.calculateCardPower(card, battleCards);
        return {
            attack: total.attack + cardPower.attack,
            defense: total.defense + cardPower.defense
        };
    }, { attack: 0, defense: 0 });
}

function checkGameEnd() {
    if (gameState.player.health <= 0) {
        alert('遊戲結束！對手獲勝！');
        resetGame();
    } else if (gameState.opponent.health <= 0) {
        alert('遊戲結束！你獲勝了！');
        resetGame();
    }
}

function resetGame() {
    // 清除計時器
    if (gameState.timerInterval) {
        clearInterval(gameState.timerInterval);
    }
    
    gameState = {
        player: {
            level: 1,
            gold: 100,
            hand: [],
            battle: [],
            maxHandSize: 6,
            health: 30
        },
        opponent: {
            level: 1,
            gold: 100,
            hand: Array.from({length: 6}, () => Math.floor(Math.random() * 18) + 1),
            battle: [],
            health: 30
        },
        availableCards: new Array(6).fill(0),
        timer: 20,
        round: 1,
        isRoundEnd: false,
        timerInterval: null
    };
    initGame();
}

function getBattleBonds(battleCards) {
    // 統計每個羈絆對應的不同卡牌類型
    const bondToCardTypeSet = {};
    battleCards.forEach(cardId => {
        const card = cardConfig.getCardInfo(cardId);
        if (!card) return;
        [card.bond1, card.bond2].forEach(bond => {
            if (!bond) return;
            if (!bondToCardTypeSet[bond]) bondToCardTypeSet[bond] = new Set();
            bondToCardTypeSet[bond].add(cardId); // 只記錄不同卡牌類型
        });
    });
    // 只顯示場上有2種及以上不同卡牌類型的羈絆
    return Object.entries(bondToCardTypeSet)
        .map(([bond, set]) => [bond, set.size])
        .filter(([bond, size]) => size >= 2);
}

function renderBonds(bonds, containerId) {
    const container = document.getElementById(containerId);
    container.innerHTML = '';
    if (bonds.length === 0) {
        container.style.display = 'none';
        return;
    }
    container.style.display = 'flex';
    bonds.forEach(([bond, count]) => {
        const item = document.createElement('span');
        item.className = 'bond-item';
        item.textContent = `${bond} ×${count}`;
        container.appendChild(item);
    });
}

function sellCard(cardId, area) {
    const cardInfo = cardConfig.getCardInfo(cardId);
    if (!cardInfo) return;
    //if (!confirm(`確定要賣出這張卡牌嗎？可獲得${cardInfo.cost}金幣`)) return;

    // 從對應區域移除
    if (area === 'hand') {
        const idx = gameState.player.hand.indexOf(cardId);
        if (idx !== -1) gameState.player.hand.splice(idx, 1);
    } else if (area === 'battle') {
        const idx = gameState.player.battle.indexOf(cardId);
        if (idx !== -1) gameState.player.battle.splice(idx, 1);
    }
    // 增加金幣
    gameState.player.gold = parseInt(gameState.player.gold) + cardInfo.cost;
    updateDisplay();
}

function updateDisplay() {
    // 更新玩家信息
    document.getElementById('player-level').textContent = gameState.player.level;
    document.getElementById('player-gold').textContent = Math.max(0, parseInt(gameState.player.gold) || 0);
    document.getElementById('player-health').textContent = gameState.player.health;
    
    // 更新對手信息
    document.getElementById('opponent-level').textContent = gameState.opponent.level;
    document.getElementById('opponent-gold').textContent = Math.max(0, parseInt(gameState.opponent.gold) || 0);
    document.getElementById('opponent-health').textContent = gameState.opponent.health;
    
    // 更新回合數顯示
    document.getElementById('round').textContent = gameState.round;
    document.getElementById('timer').textContent = gameState.timer;
    
    // 清空所有區域
    document.getElementById('player-hand').innerHTML = '';
    document.getElementById('opponent-hand').innerHTML = '';
    document.getElementById('player-battle').innerHTML = '';
    document.getElementById('opponent-battle').innerHTML = '';
    document.getElementById('available-cards').innerHTML = '';

    // 渲染玩家手牌
    gameState.player.hand.forEach(cardId => {
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        cardElement.onclick = () => playCard(cardId);
        cardElement.oncontextmenu = (e) => {
            e.preventDefault();
            sellCard(cardId, 'hand');
        };
        document.getElementById('player-hand').appendChild(cardElement);
    });

    // 渲染玩家戰場
    gameState.player.battle.forEach(cardId => {
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        
        // 檢查是否為合成卡牌
        const cardInfo = cardConfig.getCardInfo(cardId);
        if (cardInfo && cardInfo.isMerged) {
            cardElement.classList.add('merged-card');
        }
        
        cardElement.oncontextmenu = (e) => {
            e.preventDefault();
            sellCard(cardId, 'battle');
        };
        document.getElementById('player-battle').appendChild(cardElement);
    });

    // 渲染對手戰場
    gameState.opponent.battle.forEach(cardId => {
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        
        // 檢查是否為合成卡牌
        const cardInfo = cardConfig.getCardInfo(cardId);
        if (cardInfo && cardInfo.isMerged) {
            cardElement.classList.add('merged-card');
        }
        
        document.getElementById('opponent-battle').appendChild(cardElement);
    });

    // 渲染可用卡牌
    gameState.availableCards.forEach(cardId => {
        if (cardId === 0) return;
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        cardElement.onclick = () => addToHand(cardId);
        document.getElementById('available-cards').appendChild(cardElement);
    });

    // 更新羈絆顯示
    const playerBonds = getBattleBonds(gameState.player.battle);
    const opponentBonds = getBattleBonds(gameState.opponent.battle);
    renderBonds(playerBonds, 'player-bonds');
    renderBonds(opponentBonds, 'opponent-bonds');
}

function startTimer() {
    // 清除可能存在的舊計時器
    if (gameState.timerInterval) {
        clearInterval(gameState.timerInterval);
    }
    
    // 重置計時器
    gameState.timer = 20;
    document.getElementById('timer').textContent = gameState.timer;
    
    // 記錄開始時間
    const startTime = Date.now();
    
    // 設置新計時器
    gameState.timerInterval = setInterval(() => {
        // 計算實際經過的秒數
        const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
        gameState.timer = Math.max(0, 20 - elapsedSeconds);
        document.getElementById('timer').textContent = gameState.timer;
        
        // 當計時器歸零時，執行回合結束邏輯
        if (gameState.timer === 0 && !gameState.isRoundEnd) {
            endRound();
        }
    }, 100); // 每100毫秒更新一次顯示
}

initGame();